# 从精降日志中将时间戳、xyzr信息保存进csv文件

import string
import pandas as pd
import re
import csv
import time
from cmath import sqrt

SCV_FILE_NAME = 'data_detect.csv'
DETECT_FILE_NMAE = 'detect.log'
DATA = "2022-02-25"

def getDistance(x, y, z):
    return sqrt(x*x + y*y + z*z)

scv_file = open(SCV_FILE_NAME, 'w')
detect_file = open(DETECT_FILE_NMAE)

writer = csv.writer(scv_file)
writer.writerow(["data_times","detectTime", "x", "y", "z", "r", "dis"])
scv_file.close()

data_times = []
detectTime = []
x = []
y = []
z = []
r = []
distance = []

scv_file = pd.read_csv(SCV_FILE_NAME)

timePattern = re.compile(r'I([\S]*[0-9]).([\S]*)..([0-9]*.[\S]*(189|236))')
xyzPattern = re.compile(r'tvecs:.([\S]*[0-9])..([\S]*[0-9])..([\S]*[0-9])')
thetaPattern = re.compile(r'theta:.([\S]*[0-9])')
for line in detect_file.readlines():
    time_result = timePattern.search(line)
    if time_result:
        time_: string = time_result.group(2)
        data_time = DATA + " " + time_[0:8]
        #转换成时间数组
        timeArray = time.strptime(data_time, "%Y-%m-%d %H:%M:%S")
        #转换成时间戳
        timestamp = time.mktime(timeArray)
        data_time_ns = "0." + time_[9:]
        timestamp = timestamp + float(data_time_ns)
        data_times.append(data_time)
        detectTime.append(timestamp)

    xyz_result = xyzPattern.search(line)
    if xyz_result:
        x.append(xyz_result.group(2))
        y.append(xyz_result.group(1))
        z.append(xyz_result.group(3))

        distance.append(getDistance(float(xyz_result.group(2)),float(xyz_result.group(1)),float(xyz_result.group(3))).real)

    r_result = thetaPattern.search(line)
    if r_result:
        r.append(r_result.group(1))

scv_file['data_times'] = data_times
scv_file['detectTime'] = detectTime
scv_file['x'] = x
scv_file['y'] = y
scv_file['z'] = z
scv_file['r'] = r
scv_file['dis'] = distance
scv_file.to_csv(SCV_FILE_NAME, index=False, sep=',')

detect_file.close()
